package main

import (
	"fmt"
)

// 模拟一个需要资源清理的函数
func processFile(filename string) {
	// 使用defer确保资源释放
	defer func() {
		fmt.Printf("Cleaning up resources for file: %s\n", filename)
	}()

	// 模拟文件打开操作
	fmt.Printf("Opening file: %s\n", filename)

	// 模拟一个可能引发panic的错误
	if filename == "invalid.txt" {
		panic("Invalid file encountered!") // 触发panic
	}

	// 模拟文件处理操作
	fmt.Printf("Processing file: %s\n", filename)
}

// 主函数，调用processFile并捕获panic
func main() {
	// 使用defer和recover捕获panic
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("Recovered from panic: %v\n", r)
		}
	}()

	// 正常文件处理
	processFile("valid.txt")
	fmt.Println("Valid file processed successfully!")

	// 触发panic的文件处理
	processFile("invalid.txt")
	fmt.Println("This line will not be reached due to panic.")
}
